<template>
  <div class="page-manager">
    <div class="page-actions">
      <el-button type="primary" size="small" @click="goToDesigner">
        <i class="el-icon-plus"></i>
        生成新页面
      </el-button>
      <el-button type="success" size="small" @click="refreshPages">
        <i class="el-icon-refresh"></i>
        刷新列表
      </el-button>
      <el-button type="warning" size="small" @click="clearAllPages">
        <i class="el-icon-delete"></i>
        清空所有页面
      </el-button>
    </div>

    <div class="page-content">
      <el-card v-if="pageList.length === 0" class="empty-state">
        <div class="empty-content">
          <i class="el-icon-document"></i>
          <h3>暂无页面</h3>
          <p>还没有生成任何页面</p>
        </div>
      </el-card>

      <el-card v-else>
        <div slot="header" class="table-header">
          <span>页面列表 ({{ pageList.length }} 个)</span>
          <div class="table-actions">
            <el-input
              v-model="searchKeyword"
              placeholder="搜索页面名称或路由..."
              style="width: 200px; margin-right: 10px"
              clearable
              @input="handleSearch"
            >
              <i slot="prefix" class="el-input__icon el-icon-search"></i>
            </el-input>
          </div>
        </div>

        <el-table
          :data="paginatedPageList"
          style="width: 100%"
          v-loading="loading"
          stripe
        >
          <el-table-column prop="pageName" label="页面名称" width="200">
            <template slot-scope="scope">
              <span class="page-name">{{ scope.row.pageName }}</span>
            </template>
          </el-table-column>

          <el-table-column prop="routeName" label="页面路由" width="200">
            <template slot-scope="scope">
              <el-tag type="info" size="small">{{
                scope.row.routeName
              }}</el-tag>
            </template>
          </el-table-column>

          <el-table-column prop="description" label="页面描述" min-width="200">
            <template slot-scope="scope">
              <span>{{ scope.row.description || "无描述" }}</span>
            </template>
          </el-table-column>

          <el-table-column prop="creator" label="创建人" width="120">
            <template slot-scope="scope">
              <span>{{ scope.row.creator || "系统" }}</span>
            </template>
          </el-table-column>

          <el-table-column prop="createTime" label="创建时间" width="180">
            <template slot-scope="scope">
              <span>{{ formatTime(scope.row.createTime) }}</span>
            </template>
          </el-table-column>

          <el-table-column label="操作" width="480" fixed="right">
            <template slot-scope="scope">
              <div class="table-actions">
                <el-button
                  size="mini"
                  type="text"
                  @click="previewPage(scope.row)"
                  title="预览页面"
                  class="action-btn preview-btn"
                >
                  <i class="el-icon-view"></i>
                  预览
                </el-button>

                <el-button
                  size="mini"
                  type="text"
                  @click="openPurePage(scope.row)"
                  title="打开纯页面"
                  class="action-btn pure-btn"
                >
                  <i class="el-icon-document"></i>
                  纯页面
                </el-button>

                <el-button
                  size="mini"
                  type="text"
                  @click="editPage(scope.row)"
                  title="编辑页面"
                  class="action-btn edit-btn"
                >
                  <i class="el-icon-edit-outline"></i>
                  编辑
                </el-button>

                <!-- <el-button
                  size="mini"
                  type="text"
                  @click="copyPageUrl(scope.row)"
                  title="复制页面URL"
                  class="action-btn copy-btn"
                >
                  <i class="el-icon-link"></i>
                  复制链接
                </el-button> -->

                <el-button
                  size="mini"
                  type="text"
                  @click="deletePage(scope.row)"
                  title="删除页面"
                  class="action-btn delete-btn"
                >
                  <i class="el-icon-delete"></i>
                  删除
                </el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div class="pagination-wrapper" v-if="filteredPageList.length > 0">
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="currentPage"
            :page-sizes="[10, 20, 50, 100]"
            :page-size="pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="filteredPageList.length"
          >
          </el-pagination>
        </div>
      </el-card>
    </div>
  </div>
</template>

<script>
export default {
  name: "PageManager",
  data() {
    return {
      loading: false,
      pageList: [],
      filteredPageList: [],
      searchKeyword: "",
      currentPage: 1,
      pageSize: 10,
    };
  },
  computed: {
    paginatedPageList() {
      const start = (this.currentPage - 1) * this.pageSize;
      const end = start + this.pageSize;
      return this.filteredPageList.slice(start, end);
    },
  },
  async created() {
    await this.loadPages();
  },
  methods: {
    // 加载页面列表
    async loadPages() {
      this.loading = true;
      try {
        const { getPages } = await import("@/api");
        const pages = await getPages();

        this.pageList = pages.map((page) => ({
          ...page,
          creator: page.creator || "系统", // 如果没有创建人，默认为'系统'
        }));

        this.filteredPageList = [...this.pageList];
      } catch (error) {
        console.error("加载页面列表失败:", error);
        this.$message.error("加载页面列表失败: " + error.message);
        this.pageList = [];
        this.filteredPageList = [];
      } finally {
        this.loading = false;
      }
    },

    // 刷新页面列表
    refreshPages() {
      this.loadPages();
    },

    // 搜索页面
    handleSearch() {
      if (!this.searchKeyword.trim()) {
        this.filteredPageList = [...this.pageList];
      } else {
        const keyword = this.searchKeyword.toLowerCase();
        this.filteredPageList = this.pageList.filter(
          (page) =>
            page.pageName.toLowerCase().includes(keyword) ||
            page.routeName.toLowerCase().includes(keyword) ||
            (page.description &&
              page.description.toLowerCase().includes(keyword)) ||
            (page.creator && page.creator.toLowerCase().includes(keyword))
        );
      }
      this.currentPage = 1; // 重置到第一页
    },

    // 分页大小改变
    handleSizeChange(val) {
      this.pageSize = val;
      this.currentPage = 1;
    },

    // 当前页改变
    handleCurrentChange(val) {
      this.currentPage = val;
    },

    // 格式化时间
    formatTime(timeString) {
      if (!timeString) return "未知时间";
      try {
        const date = new Date(timeString);
        return date.toLocaleString("zh-CN", {
          year: "numeric",
          month: "2-digit",
          day: "2-digit",
          hour: "2-digit",
          minute: "2-digit",
        });
      } catch (error) {
        return timeString;
      }
    },

    // 跳转到设计器
    goToDesigner() {
      this.$router.push("/designer");
    },

    // 预览页面
    previewPage(page) {
      try {
        // 跳转到动态页面查看路由，传递页面ID
        this.$router.push(`/view/${page.id}`);
        // this.$message.success(`正在预览页面: ${page.pageName}`);
      } catch (error) {
        console.error("预览页面失败:", error);
        this.$message.error("预览页面失败: " + error.message);
      }
    },

    // 打开纯页面
    openPurePage(page) {
      try {
        // 跳转到纯页面路由，传递页面ID
        this.$router.push(`/pure/${page.id}`);
        // this.$message.success(`正在打开纯页面: ${page.pageName}`);
      } catch (error) {
        console.error("打开纯页面失败:", error);
        this.$message.error("打开纯页面失败: " + error.message);
      }
    },

    // 编辑页面
    editPage(page) {
      try {
        // 跳转到设计器页面，只传递页面ID进行编辑
        this.$router.push(`/designer?pageId=${page.id}`);
        this.$message.success(`正在编辑页面: ${page.pageName}`);
      } catch (error) {
        console.error("编辑页面失败:", error);
        this.$message.error("编辑页面失败: " + error.message);
      }
    },

    // 复制页面URL
    copyPageUrl(page) {
      try {
        const pageUrl = `${window.location.origin}/page/${page.routeName}`;

        // 使用现代浏览器的Clipboard API
        if (navigator.clipboard && window.isSecureContext) {
          navigator.clipboard
            .writeText(pageUrl)
            .then(() => {
              this.$message.success("页面URL已复制到剪贴板");
            })
            .catch((err) => {
              console.error("复制失败:", err);
              this.fallbackCopyToClipboard(pageUrl);
            });
        } else {
          // 降级方案
          this.fallbackCopyToClipboard(pageUrl);
        }
      } catch (error) {
        console.error("复制页面URL失败:", error);
        this.$message.error("复制失败: " + error.message);
      }
    },

    // 降级复制方案
    fallbackCopyToClipboard(text) {
      const textArea = document.createElement("textarea");
      textArea.value = text;
      document.body.appendChild(textArea);
      textArea.select();
      try {
        document.execCommand("copy");
        this.$message.success("页面URL已复制到剪贴板");
      } catch (err) {
        console.error("降级复制也失败:", err);
        this.$message.error("复制失败，请手动复制");
      }
      document.body.removeChild(textArea);
    },

    // 删除页面
    deletePage(page) {
      this.$confirm(
        `确定要删除页面 "${page.pageName}" 吗？此操作不可恢复。`,
        "删除确认",
        {
          confirmButtonText: "确定删除",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(() => {
          try {
            // 从列表中移除页面
            const index = this.pageList.findIndex((p) => p.id === page.id);
            if (index > -1) {
              this.pageList.splice(index, 1);
            }

            // 保存到localStorage
            this.savePagesToStorage();

            // 同时删除对应的页面数据
            localStorage.removeItem(`vform-page-${page.routeName}`);

            // 更新过滤列表
            this.handleSearch();

            this.$message.success("页面删除成功");
          } catch (error) {
            console.error("删除页面失败:", error);
            this.$message.error("删除页面失败: " + error.message);
          }
        })
        .catch(() => {
          // 用户取消删除
        });
    },

    // 清空所有页面
    clearAllPages() {
      this.$confirm("确定要清空所有页面吗？此操作不可恢复。", "清空确认", {
        confirmButtonText: "确定清空",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          try {
            // 清空页面列表
            this.pageList = [];
            this.filteredPageList = [];

            // 清空localStorage中的页面数据
            localStorage.removeItem("vform-generated-pages");

            // 清空所有单独的页面数据
            const keys = Object.keys(localStorage);
            keys.forEach((key) => {
              if (key.startsWith("vform-page-")) {
                localStorage.removeItem(key);
              }
            });

            this.$message.success("所有页面已清空");
          } catch (error) {
            console.error("清空页面失败:", error);
            this.$message.error("清空页面失败: " + error.message);
          }
        })
        .catch(() => {
          // 用户取消清空
        });
    },

    // 保存页面列表到localStorage
    savePagesToStorage() {
      try {
        localStorage.setItem(
          "vform-generated-pages",
          JSON.stringify(this.pageList)
        );
      } catch (error) {
        console.error("保存页面列表失败:", error);
        this.$message.error("保存页面列表失败: " + error.message);
      }
    },
  },
};
</script>

<style scoped>
.page-manager {
  padding: 20px;
  background: #f5f5f5;
  min-height: 100vh;
}

.page-actions {
  margin-bottom: 20px;
  display: flex;
  gap: 10px;
  align-items: center;
}

.page-content {
  background: white;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.empty-state {
  text-align: center;
  padding: 40px;
}

.empty-content i {
  font-size: 64px;
  color: #ddd;
  margin-bottom: 20px;
}

.empty-content h3 {
  color: #666;
  margin-bottom: 10px;
}

.empty-content p {
  color: #999;
  margin-bottom: 20px;
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.table-actions {
  display: flex;
  gap: 8px;
  align-items: center;
}

.page-name {
  font-weight: 500;
  color: #303133;
}

.action-btn {
  padding: 4px 8px !important;
  font-size: 12px !important;
  border-radius: 4px !important;
  transition: all 0.3s ease !important;
}

.action-btn:hover {
  background-color: rgba(64, 158, 255, 0.1) !important;
  transform: translateY(-1px);
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1) !important;
}

.preview-btn:hover {
  color: #67c23a !important;
  background-color: rgba(103, 194, 58, 0.1) !important;
}

.pure-btn:hover {
  color: #409eff !important;
  background-color: rgba(64, 158, 255, 0.1) !important;
}

.edit-btn:hover {
  color: #e6a23c !important;
  background-color: rgba(230, 162, 60, 0.1) !important;
}

.copy-btn:hover {
  color: #909399 !important;
  background-color: rgba(144, 147, 153, 0.1) !important;
}

.delete-btn:hover {
  color: #f56c6c !important;
  background-color: rgba(245, 108, 108, 0.1) !important;
}

.action-btn i {
  margin-right: 4px;
  font-size: 12px;
}

.pagination-wrapper {
  padding: 20px;
  text-align: right;
  border-top: 1px solid #ebeef5;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .page-manager {
    padding: 15px;
  }

  .page-actions {
    flex-direction: column;
  }

  .page-actions .el-button {
    width: 100%;
  }

  .table-header {
    flex-direction: column;
    gap: 15px;
    align-items: stretch;
  }

  .table-actions {
    justify-content: center;
  }

  .pagination-wrapper {
    text-align: center;
  }

  .table-actions {
    flex-wrap: wrap;
    gap: 4px;
  }

  .action-btn {
    font-size: 11px !important;
    padding: 3px 6px !important;
  }
}
</style>
